﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Lion.WeiXin.Handler
{
    public class CookieHelper<T> where T : class,new()
    {
        /// <summary>
        /// 写入cookie，默认保存一个月
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        public static void SaveCookie(string key, T t)
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            string strValue = json.Serialize(t);
            strValue = HttpUtility.UrlEncode(strValue);

            HttpCookie cookie = new HttpCookie(key, strValue);
            cookie.Expires = DateTime.Now.AddMonths(1);  
            //写入cookie
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 获取Cookie,无cookie null
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetCookie(string key)
        {
           
                JavaScriptSerializer json = new JavaScriptSerializer();
                HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
                if (cookie != null)
                {
                    string data = HttpUtility.UrlDecode(cookie.Value);  //解码
                    T t = json.Deserialize<T>(data); //反序列化
                    return t;
                }
                else
                {
                    return null;
                }          
        }

        /// <summary>
        /// 清除Key 键 cookie
        /// </summary>
        /// <param name="key"></param>
        public static void Clear(string key)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
            if (cookie != null)
            {
                //删除整个Cookie，只要把过期时间设置为现在
                TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
                cookie.Expires = DateTime.Now.Add(ts);
                HttpContext.Current.Response.AppendCookie(cookie);
            }
            
        }
    }
}